﻿using System;
using Tiny.Imaging.Filter.PixelLibrary;

namespace Tiny.Imaging.Filter.PointFilter
{
    public class NoiseFilter : BaseFilter.BaseFilter
    {
        private int[] _mapping;

        public NoiseFilter(float factor = 0, Func<int, int, int> blend = null, int opacity = 100)
            : base(blend, opacity)
        {
            PrePopulate(factor);
        }

        public override int Process(Rgba rgba)
        {
            rgba.R = _mapping[rgba.R];
            rgba.G = _mapping[rgba.G];
            rgba.B = _mapping[rgba.B];

            return rgba.ToInteger();
        }

        private float RandomRange(float min, float max)
        {
            return min + ((float)((new Random()).NextDouble()) * (max - min));
        }

        private void PrePopulate(float factor)
        {
            _mapping = new int[256];
            for (int i = 0; i < 256; ++i)
            {
                float rand = RandomRange(factor * -1.0f, factor);
                _mapping[i] = Blend(i, MathLibrary.MathLibrary.Clamp(i + rand));
            }
        }
    }
}